package com.ideafactory.client.views;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.VideoView;

import com.ideafactory.client.utils.FileUtils;
import com.lidroid.xutils.BitmapUtils;

import java.io.File;

public class ImageViewAutoPlay extends Thread {

    private static final String TAG = "ImageViewAutoPlay";

	private ImageView mimageView = null;

	private String[] imageStrArray = null;
	private Animation animation;
	private Handler handler;
	private VideoView videoView = null;
    private FrameLayout linearLayout;
    private BitmapUtils bitmapUtils;


	public Animation getAnimation() {
		return animation;
	}

	public void setAnimation(Animation animation) {
		this.animation = animation;
	}

	private int currentImg = 0;
	public int playTime = 1000;

	public ImageViewAutoPlay(String[] imageArray, ImageView imageView,
							 VideoView videoView, Integer playTime,FrameLayout mlinearLayout,BitmapUtils bitmapUtils) {
		this.imageStrArray = imageArray;
		this.mimageView = imageView;
		this.playTime = playTime;
		this.videoView = videoView;
        this.linearLayout=mlinearLayout;
        this.bitmapUtils=bitmapUtils;
		handler = new Handler();
	}

	public void run() {
		currentImg++;
		if (currentImg >= imageStrArray.length) {
			currentImg = 0;
		}

		String fileName = imageStrArray[currentImg];
		if (FileUtils.isVideo(fileName)) {
            mimageView.setVisibility(View.INVISIBLE);
			videoView.setVisibility(View.VISIBLE);
            linearLayout.setBackground(null);
            linearLayout.setBackgroundColor(Color.parseColor("#000000"));
            videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
                    } else if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
                    } else if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
                    }

                    handler.removeCallbacks(ImageViewAutoPlay.this);
                    handler.postDelayed(ImageViewAutoPlay.this, 0);
                    return true;
                }
            });

            videoView.setVideoPath(fileName);

            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    videoView.start();
                }
            });
		} else {
            if (videoView.getVisibility()==View.VISIBLE){
                mimageView.setBackgroundColor(Color.parseColor("#000000"));
                linearLayout.setBackground(mimageView.getDrawable());
                bitmapUtils.display(mimageView, fileName);
                mimageView.setVisibility(View.VISIBLE);
                videoView.setVisibility(View.INVISIBLE);
				Log.e(TAG, "hahahahahahhahahahahahahahahahahhahahahahahahaha " );
			}else{
                mimageView.setBackground(null);
                linearLayout.setBackground(mimageView.getDrawable());
                bitmapUtils.display(mimageView, fileName);
                mimageView.setVisibility(View.VISIBLE);
                videoView.setVisibility(View.INVISIBLE);
            }
            handler.postDelayed(this, playTime);
		}
	}

    public static Drawable zoomDrawable(Drawable drawable, int w, int h) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        // drawable转换成bitmap
        Bitmap oldbmp = drawableToBitmap(drawable);
        // 创建操作图片用的Matrix对象
        Matrix matrix = new Matrix();
        // 计算缩放比例
        float sx = ((float) w / width);
        float sy = ((float) h / height);
        // 设置缩放比例
        matrix.postScale(sx, sy);
        // 建立新的bitmap，其内容是对原bitmap的缩放后的图
        Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
                matrix, true);
        return new BitmapDrawable(newbmp);
    }
    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    public static Bitmap readBitmapAutoSize(String filePath, int outWidth, int outHeight) {
		// outWidth和outHeight是目标图片的最大宽度和高度，用作限制
		BitmapFactory.Options options;

		Bitmap bitmap = null;
		try {
			File file = new File(filePath);
			if (file.exists()) {
				options = setBitmapOption(filePath, outWidth, outHeight);
				bitmap = BitmapFactory.decodeFile(filePath,options);
				return bitmap;
			}
		} catch (OutOfMemoryError error) {
			if(bitmap!=null){
				bitmap.recycle();
			}
		}
		return null;
	}

	private static BitmapFactory.Options setBitmapOption(String file,
														 int width, int height) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inJustDecodeBounds = true;
		// 设置只是解码图片的边距，此操作目的是度量图片的实际宽度和高度
		BitmapFactory.decodeFile(file, opt);

		int outWidth = opt.outWidth; // 获得图片的实际高和宽
		int outHeight = opt.outHeight;
		opt.inDither = false;
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		// 设置加载图片的颜色数为16bit，默认是RGB_8888，表示24bit颜色和透明通道，但一般用不上
		opt.inSampleSize = 1;
		// 设置缩放比,1表示原比例，2表示原来的四分之一....
		// 计算缩放比
		if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {
			int sampleSize = (outWidth / width + outHeight / height) / 2;
			opt.inSampleSize = sampleSize;
		}
		opt.inJustDecodeBounds = false;// 最后把标志复原
		return opt;
	}



}
